package top.rainbowecho.gateway.security.authentication.social;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.Connection;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.AbstractView;
import top.rainbowecho.common.util.CommonUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.hutool.core.collection.CollUtil.isNotEmpty;

/**
 * @author rainbow
 * @since 2019/12/16 12:27
 */
@Component("connect/status")
public class SocialConnectStatusView extends AbstractView {
    private ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    @SuppressWarnings("unchecked")
    protected void renderMergedOutputModel(Map<String, Object> map, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, List<Connection<?>>> connections = (Map<String, List<Connection<?>>>) map.get("connectionMap");

        Map<String, Object> result = new HashMap<>(4);
        for (Map.Entry<String, List<Connection<?>>> entry : connections.entrySet()) {
            result.put(entry.getKey(), isNotEmpty(entry.getValue()));
        }

        String json = objectMapper.writeValueAsString(result);
        CommonUtil.jsonResponse(response, json);
    }
}
